/*商品添加/更新的路由组件*/
import React, {Component} from 'react'
import {Card, Icon, Button,Form,Input,Cascader,message} from 'antd'
import LinkButton from '../../components/link-button'
import PicturesWall from './pictureWall'
import RichTextEditor from './rich-text-editor'
import {reqCategories,reqAddaProduct} from '../../api'
const { TextArea } = Input

class ProductAddUpdate extends Component {
  state = {
    options: [],
  }
  getCascadeCategories = async (parentId)=>{
    const result = await reqCategories(parentId)
    if(result.status===0){
      const categories = result.data
      if(parentId==='0'){
        this.categories = categories
        this.initOptions()
      }else{
        this.subCategories = categories
      }
    }
  }
  loadData = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true
    await this.getCascadeCategories(targetOption.value)
    const subCategories = this.subCategories
    targetOption.loading = false;
    if(subCategories && subCategories.length>0){
      setTimeout(()=>{
        const cOptions = subCategories.map(c=>({
          value: c._id,
          label: c.name,
          isLeaf: true,
        }))
        targetOption.children = cOptions
        this.setState({
          options:[...this.state.options]
        })
      },1000)
    }else {
      targetOption.isLeaf = true
      this.setState({
        options:[...this.state.options]
      })
    }
  }
  initOptions = ()=>{
    const options = this.categories.map(c => ({
      value: c._id,
      label: c.name,
      isLeaf: false,
    }))
    this.setState({
      options
    })
  }
  submit= async ()=>{
    //先收集各项数据(name,desc,price,img,category,details)，再调用上传图片接口函数()
    const {name,desc,price,categories} = this.props.form.getFieldsValue()
    const imgs = this.refs.pw.getImgs()
    const details = this.refs.editor.getDetail()
    console.log(categories.length)

    let pCategoryId = ''
    let categoryId = ''
    if(categories.length == 1 ){
      pCategoryId = '0'
      categoryId = categories[0]
    }else {
      pCategoryId = categories[0]
      categoryId = categories[1]
    }

    const product = {name,desc,price,imgs,details,categoryId,pCategoryId}
    const result = await reqAddaProduct(product)
    if(result.status===0) {
      message.success('Product Added Successfully')
      this.props.history.goBack()
    } else {
      message.success('Failed to add this product')
    }
  }
  componentDidMount() {
    this.getCascadeCategories('0')
  }


  render() {
    const {options} = this.state
    const {getFieldDecorator} = this.props.form
    const title = (<span>
        <LinkButton onClick={() => this.props.history.goBack()}>
          <Icon type='arrow-left' style={{fontSize: 20, marginRight: 10}}/>
        </LinkButton>
        Add a product
      </span>)
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 10},
    }
    return(
      <Card title={title}>
        <Form>
          <Form.Item
            label="Product Name: "
            {...formItemLayout}
          >
            {getFieldDecorator('name', {
              initialValue : '',
              rules: [{
                required: true,
                message: 'Please input your product name!',
              }],
            })(
              <Input placeholder='Please enter the product name'/>
            )}
          </Form.Item>
          <Form.Item
            label="Description: "
            {...formItemLayout}
          >
            {getFieldDecorator('desc', {
            })(
              <TextArea rows={5} placeholder='Please describe your product'/>
            )}
          </Form.Item>
          <Form.Item
            label="Product Price: "
            labelCol= {{span: 4}}
            wrapperCol= {{span: 2}}
          >
            {getFieldDecorator('price', {

            })(
              <Input
                addonBefore='$'
                placeholder='dollar'
              />
            )}
          </Form.Item>
          <Form.Item
            label="Category: "
            labelCol= {{span: 4}}
            wrapperCol= {{span: 4}}
          >
            {getFieldDecorator('categories', {

            })(
              <Cascader
                options={options}
                loadData={this.loadData}
              />,
            )}
          </Form.Item>
          <Form.Item
            label="Product Images: "
            {...formItemLayout}
          >
            <PicturesWall ref='pw'/>
          </Form.Item>
          <Form.Item
            label="Product Details: "
            labelCol = {{span: 4}}
            wrapperCol = {{span: 15}}
          >
            <RichTextEditor ref='editor'/>
          </Form.Item>
        </Form>
        <Button
          type='primary'
          onClick={this.submit}
        >
          Submit
        </Button>
      </Card>
    )
  }
}
export default Form.create()(ProductAddUpdate)

/*
"status": 1,
        "imgs": [],
        "_id": "5cb051681280a92a1c56b3cc",
        "categoryId": "5c2ed65df352726338607049",
        "pCategoryId": "5c2ed64cf352726338607048",
        "name": "商品31",
        "price": 300,
        "desc": "商品31描述",
*/
/*
"list": [
            {
                "status": 1,
                "imgs": [
                    "image-1554885238529.png"
                ],
                "_id": "5cadaa95e7745d2708344ba4",
                "name": "Apple iPhone XR (A2108) ",
                "desc": "128GB Black 4G",
                "price": 899,
                "pCategoryId": "5cad9d02e7745d2708344ba0",
                "categoryId": "5cad9d11e7745d2708344ba1",
                "detail": "<ul......",
                "__v": 0
            }
*/